#include "rating.hh"
#include <string>
#include <unordered_map>
#include <iostream>
#include <algorithm>

Rating::Rating(const std::string& line) : 
    _attrs
    {
        {'x', 0},
        {'m', 0},
        {'a', 0},
        {'s', 0},
    }
{
    // e.g: "{x=787,m=2655,a=1222,s=2876}"
    // First and last are '{xxx}'
    std::size_t begin {1};
    const std::size_t maxIndex {line.size() - 2};

    while (begin <= maxIndex) 
    {
        if (line[begin] != '=')
        {
            begin += 1;
            continue;
        }
        const char token {line[begin - 1]};
        this->_attrs[token] = std::atoi(&(line[begin + 1]));
        begin += 1;
    }
}

void Rating::print() const
{
    std::cout << '{';

    bool firstFlag {true};
    std::for_each(
        this->_attrs.cbegin(), 
        this->_attrs.cend(), 
        [&firstFlag] (const std::pair<char, int>& kv) {
            if (!firstFlag) std::cout << ',';
            else firstFlag = false;
            std::cout << kv.first << '=' << kv.second;
        }
    );
    std::cout << '}';
}

int Rating::attr(const char type) const
{
    return this->_attrs.at(type);
}